package org.adream.account.service;

import java.util.List;

import org.adream.account.dao.UserAddressDao;
import org.adream.account.entity.UserAddressEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserAddressService {
	@Autowired
	UserAddressDao userAddressDao;
	
	public List<UserAddressEntity> searchByUid(String uid) {
		if(StringUtils.isEmpty(uid)) {
			return null;
		}
		return userAddressDao.searchByUid(uid);
	}

	public int add(UserAddressEntity addressEntity){
		if(addressEntity == null) {
			return 0;
		}
		if(addressEntity.getIsDefault()) {
			removeDefaultByUid(addressEntity.getUid());
		}
		return userAddressDao.insert(addressEntity);
	}

	public int deleteById(Integer uaId) {
		return userAddressDao.deleteById(uaId);
	}
	
	public int update(UserAddressEntity addressEntity) {
		if(addressEntity == null) {
			return 0;
		}
		if(addressEntity.getIsDefault()) {
			removeDefaultByUid(addressEntity.getUid());
		}
		return userAddressDao.update(addressEntity);
	}

	public UserAddressEntity searchByUaId(Integer uaId) {
		return userAddressDao.searchByUaId(uaId);
	}
	
	/**
	 * 根据业务 如果 新建或者更新时 存在默认值的设定 就去除全部默认地址
	 * 根据UID 去除默认地址
	 */
	private void removeDefaultByUid(String uid) {
		userAddressDao.removeDefaultByUid(uid);
	}
	
}
